package com.xiaowu.xblog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowu.xblog.entity.LoginUser;
import com.xiaowu.xblog.entity.SysUser;
import com.xiaowu.xblog.repository.SysUserRepository;
import com.xiaowu.xblog.utils.LoginTypeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @description:
 * @author: xiaowu
 * @time: 2025/6/25 0:02
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class SysUserDetailsService implements UserDetailsService {

//    private final UserMapper userMapper;
    private final SysUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String loginInput) throws UsernameNotFoundException {
        if (!StringUtils.hasText(loginInput)) {
            log.warn("登录失败，输入为空");
            throw new UsernameNotFoundException("登录名不能为空");
        }

        LambdaQueryWrapper<SysUser> queryWrapper = LoginTypeUtil.isEmail(loginInput)
                ? new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, loginInput)
                : new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, loginInput);

//        UserPO user = userMapper.selectOne(queryWrapper);
        SysUser user = userRepository.getOne(queryWrapper);

        if (user == null) {
            log.warn("登录失败，未找到用户: {}", maskLoginInput(loginInput));
            throw new UsernameNotFoundException("账号不存在: " + loginInput);
        }

        return new LoginUser(user);
    }

    private String maskLoginInput(String input) {
        if (LoginTypeUtil.isEmail(input)) {
            int atIndex = input.indexOf('@');
            if (atIndex <= 1) return "***@***";
            return input.charAt(0) + "***" + input.substring(atIndex - 1);
        }
        return input.length() <= 2 ? "**" : input.charAt(0) + "**" + input.charAt(input.length() - 1);
    }
}
